import React, {useEffect, useState} from 'react'
import {Form, Button, TreeSelect, Input, Modal, Row, Col, message, Switch, Select} from 'antd'
import moment from 'moment'
import {connect} from 'umi'
import {getDepartmentUser} from '@/pages/components/service'
import { getSelectProgram, getScoreUpdateDetail, getEmployessInfoByCode } from '../../service'
import ImportPerson from "@/pages/ScoreOf360/List/components/ImportPerson";
import SelectUserModal from "@/pages/components/SelectUserModal";
import store from 'store2'

const FormItem = Form.Item;
const {Option} = Select;

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 24,
  lg: 24,
  md: 24,
  sm: 24,
  xs: 24,
};

const CreateForm = (props) => {

  const {visible, onSubmit, onCancel, current, currentUser, global = {}} = props;
  const {options = {}} = global;
  const {orgTree = []} = options;
  const [form] = Form.useForm();
  const [scoreTypes, setScoreTypes] = useState([]);
  const [dataTree, setDataTree] = useState([]);
  const [importVisible, setImportVisible] = useState(false);
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [importType, setImportType] = useState();
  const [superiorData, setSuperiorData] = useState([]);
  const [sameLevelData, setSameLevelData] = useState([]);
  const [subordinateData, setSubordinateData] = useState([]);
  const [currentScore, setCurrentScore] = useState({});
  const [selectType,setSelectType] = useState(1);

  const recursiveSetSelectable = (list) => {
    list.forEach(item => {
      item.selectable = false;
      recursiveSetSelectable(item.children)
    })
  };

  const groupPersonByUnit = (personList) => {
    let filterList = Array.from(new Set(personList.map(item => item.unitId)));
    let unitPerson = filterList.map(item => ({unitId:item,children:[]}));
    personList.forEach(itemA => {
      for(let i=0; i<unitPerson.length; i++){
        if (unitPerson[i].unitId===itemA.unitId){
          unitPerson[i].children.push({title: itemA.name, value: itemA.oid, isLeaf: true});
          break
        }
      }
    });
    return unitPerson;
  };

  const setInitTree = (tree,list) => {
    tree.forEach(item => {
      for(let i=0; i<list.length; i++){
        if (item.value===list[i].unitId){
          item.children = list[i].children;
          list.splice(i,1);
          break;
        }
      }
      if (item.children?.length>0)
        setInitTree(item.children,list);
    });
  };

  useEffect(() => {
    getSelectProgram().then(res => {
      setScoreTypes(res);
    })
  }, []);

  useEffect(() => {
    if (visible && orgTree) {
      let localOrgTree = JSON.parse(JSON.stringify(orgTree));
      if (current){
        getScoreUpdateDetail(current.id).then(res =>{
          if (res){
            let personList = [{
              name: res.name,
              unitId: parseInt(res.unitId),
              oid: res.oid,
            }];//.concat(res.sameLevelList, res.subordinateList, res.superiorList);
            setInitTree(localOrgTree,groupPersonByUnit(personList));
            setDataTree(localOrgTree);
            let { oid, programId, superiorList, subordinateList, sameLevelList, isAppraisal } = res;
            setSuperiorData(superiorList);
            setSubordinateData(subordinateList);
            setSameLevelData(sameLevelList);
            setRange({value:res.programId});
            let initData = {
              oid,
              programId,
              sameLevelList: sameLevelList.map(item => item.oid),
              superiorList: superiorList.map(item => item.oid),
              subordinateList: subordinateList.map(item => item.oid),
              isAppraisal: isAppraisal,
              name:res.name
            };
            form.setFieldsValue(initData);
          }
        });
      } else {
        const fieldsValue = store('scoreof360-list-create')
        form.setFieldsValue(fieldsValue);
        recursiveSetSelectable(localOrgTree);
        setDataTree(localOrgTree);
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
    setImportType(null);
  };

  const onFormReset = async () => {
    form.resetFields();
  };

  const onFormSave = async () => {
    const fieldsValue = await form.validateFields();
    store('scoreof360-list-create',fieldsValue)
  };

  const handleNext = async () => {
    const fieldsValue = await form.validateFields();
    let id = current ? current.id : null;
    let {isAppraisal, ...restValue} = fieldsValue;
    onSubmit({id, isAppraisal: isAppraisal ? 1 : 0, ...restValue});
    form.resetFields();
  };

  const openImportModal = (type) => {
    setImportVisible(true);
    setImportType(type);
  };

  const setRaterData = (dataList) => {
    switch (importType) {
      case 'superiorList':
        setSuperiorData(Array.from(new Set([...superiorData,...dataList])));
        break;
      case 'sameLevelList':
        setSameLevelData(Array.from(new Set([...sameLevelData,...dataList])));
        break;
      case 'subordinateList':
        setSubordinateData(Array.from(new Set([...subordinateData,...dataList])));
        break;
    }
  };

  const importPerson = (codes)=> {
    setImportVisible(false);
    getEmployessInfoByCode(codes).then(res => {
      message.success(res.notFoundStr);
      if (res.employeeInfoEntityList && res.employeeInfoEntityList.length>0){
        let obj = {};
        let originalList = form.getFieldValue(importType);
        originalList = originalList ? originalList : [];
        let personList = res.employeeInfoEntityList.map(item=>({name: item.name, oid: item.oid}));
        setRaterData(personList);
        obj[importType] = Array.from(new Set([...originalList,...personList.map(item => item.oid)]));
        form.setFieldsValue(obj);
      }
      setImportType(null);
    })
  };

  const cancelImport = () => {
    setImportVisible(false);
    setImportType(null);
  };

  const addUserInTree = (tree, value, userList) => {
    for (let i = 0; i < tree.length; i++) {
      if (tree[i].value === value) {
        tree[i].children = userList;
      } else if (tree[i].children?.length > 0) {
        addUserInTree(tree[i].children, value, userList);
      }
    }
  };

  const loadUserData = treeNode => new Promise(resolve => {
    if (treeNode.children.length < 1 || !treeNode.children[0].pareorgId) {
      let tree = JSON.parse(JSON.stringify(dataTree));
      getDepartmentUser(treeNode.value).then(res => {
        if (res) {
          let usersNode = res.map(item => {
            return {
              title: item.name,
              value: item.oid,
              isLeaf: true
            }
          });
          addUserInTree(tree, treeNode.value, usersNode);
          setDataTree(tree);
          setTimeout(() => {
            resolve();
          }, 300);
        }
      });
    } else {
      resolve();
    }
  });

  const showSelectUserModal = (type) => {
    setUserModalVisible(true);
    setImportType(type);
    setSelectType(type === 'oid' ? 0 : 1);
  };

  const confirmSelectUser = (infos) => {
    if (infos.length>0) {
      let obj = {};
      let originalList = form.getFieldValue(importType);
      originalList = originalList || [];
      let needsUserList = new Set(infos.map(info => ({oid: info.oid, name: info.name})));
      let needsUserOidList = infos.map(info =>(info.oid));
      setRaterData(needsUserList);
      obj[importType] = Array.from(new Set([...originalList,...needsUserOidList]));
      if(importType === 'oid'){
        let {oid,name} = infos[0];
        form.setFieldsValue({oid:oid,name:name});
      }else{
        form.setFieldsValue(obj);
      }
      setUserModalVisible(false);
      setImportType(null);
    } else {
      message.error('请选择人员!')
    }
  };

  const cancelSelectUser = () => {
    setUserModalVisible(false);
    setImportType(null);
  };

  const setRange = (option) => {
    setCurrentScore(scoreTypes.find(item=>item.id===option.value))
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle} style={{paddingLeft: '23%'}}>
            <FormItem labelCol={{span: 7}} style={{width:'66.5%'}} name="applyName" label="创建人">
              <Input disabled/>
            </FormItem>
          </Col>
          <Col span={0}>
            <FormItem name="oid" label="">
              <Input disabled/>
            </FormItem>
          </Col>
          <Col {...colStyle} style={{paddingLeft: '23%',display: 'flex'}}>
            <Form.Item labelCol={{span: 7}} style={{width:'66.5%'}} name='name' label="被评分人"
                       rules={[{required: true, message: '被评分人不能为空'}]}>
              {/*<TreeSelect*/}
              {/*  style={{width: '100%'}}*/}
              {/*  dropdownStyle={{maxHeight: 400, overflow: 'auto'}}*/}
              {/*  placeholder="请选择被评分人"*/}
              {/*  treeData={dataTree}*/}
              {/*  loadData={loadUserData}*/}
              {/*/>*/}
              <Input className='widthStyle' disabled placeholder="请添加被评分人"/>
            </Form.Item>
            <Button style={{marginLeft:'5px'}} onClick={()=>showSelectUserModal('oid')}>添加</Button>
          </Col>
          <Col {...colStyle} style={{paddingLeft: '23%'}}>
            <FormItem labelCol={{span: 7}} style={{width:'66.5%'}} name="programId" label="评分类型"
                      rules={[{required: true, message: '评分类型不能为空'}]}>
              <Select style={{width: '100%'}} onSelect={(value,option) => setRange(option)}>
                {
                  scoreTypes.length > 0 && scoreTypes.map((item, index) => {
                    return <Option key={index} value={item.id}>{item.programName}</Option>
                  })
                }
              </Select>
            </FormItem>
          </Col>
          {
            currentScore?.superiorWeights !== 0 &&
            <Col {...colStyle} style={{paddingLeft: '23%',display: 'flex'}}>
              <Form.Item labelCol={{span: 7}} style={{width:'66.5%'}} name='superiorList'
                         label={`上级评分人${currentScore?.superiorWeights ? `(${currentScore.superiorWeights}%)`: ``}`}>
                <Select mode="multiple">
                  {superiorData.map(item => (<Option key={item.oid} value={item.oid}>{item.name}</Option>))}
                </Select>
              </Form.Item>
              <Button style={{marginLeft:'5px'}} onClick={()=>showSelectUserModal('superiorList')}>添加</Button>
              <Button loading={importType==='superiorList'} type='primary' style={{marginLeft:'5px'}} onClick={() => openImportModal('superiorList')}>批量</Button>
            </Col>
          }
          {
            currentScore?.sameLevelWeights !== 0 &&
            <Col {...colStyle} style={{paddingLeft: '23%',display: 'flex'}}>
              <Form.Item labelCol={{span: 7}} style={{width:'66.5%'}} name='sameLevelList'
                         label={`同级评分人${currentScore?.sameLevelWeights ? `(${currentScore.sameLevelWeights}%)`: ``}`}>
                <Select mode="multiple">
                  {sameLevelData.map(item => (<Option key={item.oid} value={item.oid}>{item.name}</Option>))}
                </Select>
              </Form.Item>
              <Button style={{marginLeft:'5px'}} onClick={()=>showSelectUserModal('sameLevelList')}>添加</Button>
              <Button loading={importType==='sameLevelList'} type='primary' style={{marginLeft:'5px'}} onClick={() => openImportModal('sameLevelList')}>批量</Button>
            </Col>
          }
          {
            currentScore?.subordinateWeights !== 0 &&
            <Col {...colStyle} style={{paddingLeft: '23%',display: 'flex'}}>
              <Form.Item labelCol={{span: 7}} style={{width:'66.5%'}} name='subordinateList'
                         label={`下级评分人${currentScore?.subordinateWeights ? `(${currentScore.subordinateWeights}%)`: ``}`}>
                <Select mode="multiple">
                  {subordinateData.map(item => (<Option key={item.oid} value={item.oid}>{item.name}</Option>))}
                </Select>
              </Form.Item>
              <Button style={{marginLeft:'5px'}} onClick={()=>showSelectUserModal('subordinateList')}>添加</Button>
              <Button loading={importType==='subordinateList'} type='primary' style={{marginLeft:'5px'}} onClick={() => openImportModal('subordinateList')}>批量</Button>
            </Col>
          }
          <Col {...colStyle} style={{paddingLeft: '23%'}}>
            <Form.Item labelCol={{span: 7}} style={{width:'66.5%'}} name='isAppraisal' valuePropName="checked"
                       label={`是否自评${currentScore?.myWeights ? `(${currentScore.myWeights}%)`: ``}`} >
              <Switch/>
            </Form.Item>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button onClick={() => onFormReset()}>重置</Button>
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Button type="primary" onClick={() => handleNext()}>完成</Button>
      </>
    )
  };

  return (
    <Modal
      width='60%'
      destroyOnClose
      title="360评分"
      visible={visible}
      footer={renderFooter()}
      onOk={handleNext}
      onCancel={onFormCancel}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        initialValues={{applyName: current ? current.createName : currentUser.name}}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
        <ImportPerson
          visible={importVisible}
          onSubmit={importPerson}
          onCancel={cancelImport}
        />
      <SelectUserModal
        selectType={selectType}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
      />
    </Modal>
  )
};

export default connect(({user, global}) => ({
  global,
  currentUser: user.currentUser,
}))(CreateForm)
